# -*- coding:utf8 -*- #
# -----------------------------------------------------------------------------------
# ProjectName:  smart-water-iot-test
# FileName:     requestsUtil.py
# Author  :     
# Datetime:     2022/8/29 13:40
# Description：
# -----------------------------------------------------------------------------------

from typing import Any, Union

import requests
from requests import Response
from common.util.logUtil.logUtil import LoggerUtil

logger = LoggerUtil()


class RequestsUtil:
    """
    基于项目中的接口的各种请求方法和传参方式，封装通用的方法
    """
    _session = requests.session()

    def send_request(self, method: str, url: str, params: [Any], parameterFormat: str = "data",
                     **kwargs: [Any]) -> Union[dict, Response]:
        """
        针对不同请求方法和传参方式进行判断，调用Session对象的方法实现请求
        :param method: 请求方式
        :param url: 地址
        :param params: 参数
        :param parameterFormat: 参数请求方式，默认data
        :param kwargs:关键字传参
        :return: 返回json响应内容
        """
        try:
            method = method.upper()
            parameterFormat = parameterFormat.lower()
            if method == "GET":
                return self._session.request(method, url, params=params, **kwargs).json()
            elif method == "POST":
                if parameterFormat == "data":
                    return self._session.request(method, url, data=params, **kwargs).json()
                else:
                    return self._session.request(method, url, json=params, **kwargs).json()
            else:
                print("只支持GET/POST两种方法！！！")
        except Exception as e:
            logger.error(e)
            raise e
        except KeyError as e:
            logger.error(e)
            raise e

    @property
    def session(self):
        return self._session
